package cms.simmytech.service;

import java.util.ArrayList;
import java.util.List;

import cms.simmytech.model.SysPermission;
import cms.simmytech.model.SysUser;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;



@Service
public class CustomUserService implements UserDetailsService { // 自定义UserDetailsService

	Log log=LogFactory.getLog(CustomUserService.class);
	
	@Autowired
	private UserService userService;

	public UserDetails loadUserByUsername(String username) {
		SysUser user = userService.getUserByUserName(username);
		if (user != null) {
			if (user.getState().intValue()==-1){
				throw new UsernameNotFoundException("admin: " + username + "  not allow!");
			}

			List<SysPermission> permissions = userService.getPermissionByUserId(user.getId());
			List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
			for (SysPermission permission : permissions) {
				if (permission != null && permission.getName() != null) {
					GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission.getName());
					grantedAuthorities.add(grantedAuthority);
				}
			}
			userService.updateUserLogintime(user.getId());
			return new User(user.getUsername(), user.getPassword(), grantedAuthorities);
		} else {
			throw new UsernameNotFoundException("admin: " + username + " do not exist!");
		}
	}

}
